from flask import Flask,request,jsonify,Blueprint
from views.add_cates import  bp_cates
# 导入jwt 进行token解密
from utils.jwt_c import jwte


def create_app():
    app = Flask(__name__)
    with app.app_context():
        pass
    return app
app = create_app()

# app = Flask(__name__)

# 导入配置文件
from config import Config
# 加载配置文件
app.config.from_object(Config)
#解决跨域
from flask_cors import CORS
CORS(app)
# 导入数据库
from db import db1
# 导入蓝图
from workss import  bp_work
# 导入用户蓝图
from views.adminuser import  adminusers
# 导入登录蓝图
from views.login_adminuser import bp_auser
from views.users import  bp_users
app.register_blueprint(adminusers,url_prefix="/admin/")
app.register_blueprint(bp_work,url_prefix="/work/")
app.register_blueprint(bp_cates,url_prefix='/cates/')
# 注册管理员
app.register_blueprint(bp_auser,url_prefix='/auser/')
# 用户蓝图
app.register_blueprint(bp_users,url_prefix="/users/")


# 防止循环

    # app存放在create李   然后在users中导入 from flask import current_app as app




app.config['SECRET_KEY'] = '123123wadaws'
# 下面是SMTP服务器配置
app.config['MAIL_SERVER'] = 'smtp.163.com'  # 电子邮件服务器的主机名或IP地址
app.config['MAIL_PORT'] = '25'  # 电子邮件服务器的端口
app.config['MAIL_USE_TLS'] = True  # 启用传输层安全
app.config['MAIL_USERNAME'] = 'Jch_676139664@163.com'  # os.environ.get('MAIL_USERNAME') #邮件账户用户名
app.config['MAIL_PASSWORD'] = 'XXOWYMNBUMGHEBOV'  # os.environ.get('MAIL_PASSWORD') #邮件账户的密码





# 测试添加展示 
# @app.route('/test')
# def test():
    # sql1 = "insert into test values(0,'焦长豪')"
    # db1.update(sql1)
    # sql = "select * from test"
    # res = db1.find_all(sql)
    # return jsonify({"list":res})
    # # return res
    # return 'ok'


import time
# 拦截器
# 每次请求判断token是否存在 是否过期
@app.before_request
def before_request():
    # 401 过期    403无权限访问
    # 查看路径 request.path
    # print(request.path)
    # # 查看是否携带token
    # print(request.headers['Token'])
    # print(request.path)
    white = ['/auser/sendmsm/','/auser/mobile_login/']
    if request.path not in white:
        # 获取token
        try:
            # 获取头部token
            token = request.headers['Token']
            # token = {"data":{"id":1,"iat":time.time(),"exp":3600}}
        except Exception as e:
            return jsonify({"code": 403, 'msg': '无权限访问'})

        payload = jwte.j_d(token)
        # print(payload)
        if payload:
            # token创建时间
            ctime = payload['data']['iat']
            # token过期时间
            exptime = payload['data']['exp']
            # 当前时间-创建时间  > token的过期时间  说明token过期
            if int(time.time()-ctime) > exptime:

                return jsonify({"code":401,'msg':'token已过期'})
        # 判断token是否比对成功  或者说 被篡改了吗
        if jwte.j_decode(token) == False:
            return jsonify({"code":403,"msg":"请不要篡改token"})











# 跨域
if __name__ == "__main__":
    app.run(debug=True)